import {
  Controller,
  Post,
  Delete,
  UseInterceptors,
  UploadedFile,
  UploadedFiles,
  UseGuards,
  Body,
  BadRequestException,
} from '@nestjs/common';
import { FileInterceptor, FilesInterceptor } from '@nestjs/platform-express';
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
import { UploadService } from './upload.service';
import type { UploadedFile as FileUpload } from './upload.types';

@Controller('upload')
@UseGuards(JwtAuthGuard)
export class UploadController {
  constructor(private readonly uploadService: UploadService) {}

  /**
   * 上传单个文件（默认路由，用于头像等）
   */
  @Post()
  @UseInterceptors(FileInterceptor('file'))
  async upload(
    @UploadedFile() file: FileUpload,
    @Body('type') type?: 'tool' | 'avatar' | 'temp',
  ) {
    if (!file) {
      throw new BadRequestException('请选择要上传的文件');
    }

    const result = await this.uploadService.uploadFile(file, type || 'avatar');
    
    // 直接返回 url，方便前端使用
    return result;
  }

  /**
   * 上传单个文件（详细响应）
   */
  @Post('single')
  @UseInterceptors(FileInterceptor('file'))
  async uploadSingle(
    @UploadedFile() file: FileUpload,
    @Body('type') type?: 'tool' | 'avatar' | 'temp',
  ) {
    if (!file) {
      throw new BadRequestException('请选择要上传的文件');
    }

    const result = await this.uploadService.uploadFile(file, type || 'temp');
    
    return {
      success: true,
      message: '上传成功',
      data: result,
    };
  }

  /**
   * 上传多个文件
   */
  @Post('multiple')
  @UseInterceptors(FilesInterceptor('files', 10)) // 最多10个文件
  async uploadMultiple(
    @UploadedFiles() files: FileUpload[],
    @Body('type') type?: 'tool' | 'avatar' | 'temp',
  ) {
    if (!files || files.length === 0) {
      throw new BadRequestException('请选择要上传的文件');
    }

    const results = await this.uploadService.uploadFiles(files, type || 'temp');
    
    return {
      success: true,
      message: `成功上传 ${results.length} 个文件`,
      data: results,
    };
  }

  /**
   * 删除文件
   */
  @Delete()
  async deleteFile(@Body('url') url: string) {
    if (!url) {
      throw new BadRequestException('请提供文件URL');
    }

    const success = await this.uploadService.deleteFile(url);
    
    return {
      success,
      message: success ? '删除成功' : '文件不存在或删除失败',
    };
  }
}


